/**
 * Copyright (C)  2011  chen wei hua.
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 2.0
 * or any later version published by the Free Software Foundation;
 * with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU Free Documentation License".
 */
package com.javaeye.delivery.service;

import java.util.List;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.javaeye.delivery.dao.DeliveryOrderDAO;
import com.javaeye.delivery.dao.OrderDAO;
import com.javaeye.delivery.dao.OrderDetailBatchInfoDAO;
import com.javaeye.delivery.dao.ReasonDAO;
import com.javaeye.delivery.dto.CustomerOrder;
import com.javaeye.delivery.dto.DeliveryOrder;
import com.javaeye.delivery.dto.DeliveryOrderDetail;
import com.javaeye.delivery.dto.OrderDetailBatchInfo;
import com.javaeye.procurement.dao.StatementRecordDAO;
import com.javaeye.procurement.dto.StatementRecord;
import com.javaeye.store.dao.MaterialsBatchDetailDAO;
import com.javaeye.store.dao.MaterialsChangeDetailDAO;
import com.javaeye.store.dao.MaterialsSKUDetailDAO;
import com.javaeye.store.dto.MaterialsBatchDetail;
import com.javaeye.store.dto.MaterialsChangeDetail;
import com.javaeye.store.dto.MaterialsSKUDetail;
import com.javaeye.delivery.dto.Reason;
import com.javaeye.common.util.DateUtils;
import com.javaeye.common.web.PageInfo;
import com.javaeye.delivery.web.OrderCondition;

public class DeliveryOrderService implements IDeliveryOrderService {
	
	private static Log log = LogFactory.getLog(DeliveryOrderService.class);
	
	private DeliveryOrderDAO dao;
	
	private StatementRecordDAO statementRecordDao;
	
	private MaterialsSKUDetailDAO materialsSKUDetailDao;
	
	//订单明细产品生产批次
	private OrderDetailBatchInfoDAO orderDetailBatchInfoDao;
	
	//产品库存变动明细
	private MaterialsChangeDetailDAO materialsChangeDetailDao;
	
	//产品批次库存
	private MaterialsBatchDetailDAO materialsBatchDetailDao;
	
	private OrderDAO orderDao;
	
	private ReasonDAO reasonDao;
	
	public void setDao(DeliveryOrderDAO dao) {
		this.dao = dao;
	}
	
	public void setMaterialsSKUDetailDao(MaterialsSKUDetailDAO materialsSKUDetailDao) {
		this.materialsSKUDetailDao = materialsSKUDetailDao;
	}

	public void setOrderDetailBatchInfoDao(
			OrderDetailBatchInfoDAO orderDetailBatchInfoDao) {
		this.orderDetailBatchInfoDao = orderDetailBatchInfoDao;
	}

	public void setMaterialsChangeDetailDao(
			MaterialsChangeDetailDAO materialsChangeDetailDao) {
		this.materialsChangeDetailDao = materialsChangeDetailDao;
	}

	public void setMaterialsBatchDetailDao(
			MaterialsBatchDetailDAO materialsBatchDetailDao) {
		this.materialsBatchDetailDao = materialsBatchDetailDao;
	}

	public void setStatementRecordDao(StatementRecordDAO statementRecordDao) {
		this.statementRecordDao = statementRecordDao;
	}

	public void setOrderDao(OrderDAO orderDao) {
		this.orderDao = orderDao;
	}
	
	public void setReasonDao(ReasonDAO reasonDao) {
		this.reasonDao = reasonDao;
	}

	@SuppressWarnings("unchecked")
	public List getOrderList(OrderCondition condition, PageInfo pageInfo) {
		List<DeliveryOrder> result = dao.getPageData(condition, pageInfo);
		if (result == null || result.size() == 0) {
			log.warn("数据库中未找到指定的成品交运单信息");
		}
		return result;
	}

	public DeliveryOrder getDeliveryOrder(String orderId) {
		DeliveryOrder order = dao.getDeliveryOrder(orderId);
		if (order == null) {
			log.warn("数据库中未找到指定的成品交运单信息，单号：" + orderId);
			return new DeliveryOrder();
		}
		long count = reasonDao.getReasonCount(order.getId());
		order.setReasons(count);
		return order;
	}
	
	public void save(DeliveryOrder order) {
		dao.save(order);
		//生成应收款记录
		StatementRecord record = new StatementRecord();
		record.setInOutType(StatementRecord.STATEMENT_IN_OUT_TYPE_IN);
		record.setRecordType(StatementRecord.STATEMENT_RECORD_TYPE_ADD);
		record.setOrderId(order.getOrderNo());
		//record.setRecordDate(order.getDeliveryDate());
		record.setCustomerId(order.getCustomId());
		record.setCustomerName(order.getCustomName());
		record.setAmount(order.getTotleAmount());
		statementRecordDao.saveStatementRecord(record);
		
		//更新出货单为已经完成
		CustomerOrder customerOrder = orderDao.getOrderBaseInfo(order.getId());
		customerOrder.setStatus(CustomerOrder.ORDER_STATES_END);
		orderDao.saveOrder(customerOrder);
		
		double hours = DateUtils.getDateOffsetHour(customerOrder.getOutDate(), DateUtils.now());
		if (hours > Reason.LATER_HOUR) {
			Reason reason = new Reason(Reason.REASON_CATEGORY_STORE, 
					order.getId(),
					"仓库发货在出货单的出货日期" + Reason.LATER_HOUR + "个小时之后");
			reasonDao.saveReason(reason);
		}
		
		//String purchaseOrderId = order.getPurchaseOrderId();
		Set<DeliveryOrderDetail> details = order.getOrderDetails();
		for (DeliveryOrderDetail detail : details) {
			int productId = detail.getProductId();
			
			//更新实时库存数量
			MaterialsSKUDetail skuDetail = materialsSKUDetailDao.getMaterialsSKUDetail(productId);
			skuDetail.setNumber(skuDetail.getNumber() - detail.getNumber());
			materialsSKUDetailDao.saveMaterialsSKUDetail(skuDetail);
			
			List<OrderDetailBatchInfo> batchInfos = orderDetailBatchInfoDao.getBatchInfo(order.getId(), productId);
			for (OrderDetailBatchInfo batchInfo : batchInfos) {
				//记录库存变动明细表
				MaterialsChangeDetail changeDetail = new MaterialsChangeDetail();
				changeDetail.setMaterialsId(productId);
				changeDetail.setVoucherNo(order.getId());
				changeDetail.setChangeType(MaterialsChangeDetail.PRODUCT_OUTSTORE);
				changeDetail.setBatchNo(batchInfo.getBatchNo());
				changeDetail.setNumber(batchInfo.getNumber());
				materialsChangeDetailDao.save(changeDetail);
				
				//更新批次库存数量
				MaterialsBatchDetail batchDetail = materialsBatchDetailDao.getBatchDetail(
						productId, batchInfo.getBatchNo());
				batchDetail.setOutNumber(batchDetail.getOutNumber() - batchInfo.getNumber());
				materialsBatchDetailDao.save(batchDetail);
			}
			
			/*//更新订单表里的已经入库数量
			PurchaseOrderDetail purchaseOrderdetail = purchaseOrderDetailDao
					.getPurchaseOrderDetail(purchaseOrderId, productId);
			purchaseOrderdetail.setDeliveryNumber(purchaseOrderdetail.getDeliveryNumber() + detail.getNumber());
			purchaseOrderDetailDao.savePurchaseOrderDetail(purchaseOrderdetail);
			*/
		}
		
		/*//如果全部发货完成更新订单表的状态
		PurchaseOrder purchaseOrder = purchaseOrderDao.getPurchaseOrderInfo(purchaseOrderId);
		Set<PurchaseOrderDetail> alldetails = purchaseOrder.getOrderDetails();
		if (isDeliveryFinished(alldetails)) {
			purchaseOrder.setStatus(IOrderService.ORDER_STATES_END);
			purchaseOrderDao.savePurchaseOrder(purchaseOrder);
		}*/
	}
	
	/**
	 * 是否全部发货完成
	 * @param details
	 * @return
	 */
	/*private boolean isDeliveryFinished(Set<PurchaseOrderDetail> details) {
		int allCount = details.size();
		int finishCount = 0;
		for (PurchaseOrderDetail detail : details) {
			if (detail.getDeliveryNumber() >= detail.getNumber()) {
				finishCount++;
			}
		}
		return finishCount == allCount;
	}*/
}
